<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>联机狼人杀 - 实时版</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Microsoft YaHei', sans-serif; }
        body { background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d); color: #fff; min-height: 100vh; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        header { text-align: center; padding: 20px 0; margin-bottom: 30px; }
        h1 { font-size: 2.5rem; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); margin-bottom: 10px; }
        .subtitle { font-size: 1.2rem; opacity: 0.9; margin-bottom: 20px; }
        .share-link { background: rgba(255,255,255,0.2); padding: 10px; border-radius: 5px; margin: 10px 0; word-break: break-all; }
        .game-container { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 30px; }
        .panel { background: rgba(0,0,0,0.6); border-radius: 10px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); }
        .room-panel { flex: 1; min-width: 300px; }
        .game-panel { flex: 2; min-width: 500px; }
        .panel-title { font-size: 1.5rem; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid rgba(255,255,255,0.2); }
        .input-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; }
        input, select, button { width: 100%; padding: 10px; border-radius: 5px; border: none; background: rgba(255,255,255,0.9); }
        button { background: #e74c3c; color: white; font-weight: bold; cursor: pointer; transition: all 0.3s; margin-top: 10px; }
        button:hover { background: #c0392b; transform: translateY(-2px); }
        button:disabled { background: #7f8c8d; cursor: not-allowed; transform: none; }
        .player-list { list-style: none; margin-top: 15px; max-height: 200px; overflow-y: auto; }
        .player-list li { padding: 8px 10px; background: rgba(255,255,255,0.1); margin-bottom: 5px; border-radius: 5px; display: flex; justify-content: space-between; }
        .game-area { min-height: 400px; display: flex; flex-direction: column; }
        .game-info { background: rgba(0,0,0,0.4); padding: 15px; border-radius: 5px; margin-bottom: 15px; flex: 1; }
        .game-controls { display: flex; gap: 10px; }
        .game-controls button { flex: 1; }
        .role-cards { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px; }
        .role-card { background: rgba(255,255,255,0.1); border-radius: 8px; padding: 15px; width: calc(33.333% - 10px); text-align: center; transition: all 0.3s; }
        .role-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .role-card h3 { margin-bottom: 5px; color: #f1c40f; }
        .role-card.werewolf { border: 2px solid #c0392b; }
        .role-card.seer { border: 2px solid #3498db; }
        .role-card.witch { border: 2px solid #9b59b6; }
        .role-card.villager { border: 2px solid #2ecc71; }
        .chat-area { background: rgba(0,0,0,0.4); border-radius: 5px; padding: 15px; margin-top: 20px; }
        .chat-messages { height: 150px; overflow-y: auto; margin-bottom: 10px; padding: 10px; background: rgba(0,0,0,0.3); border-radius: 5px; }
        .chat-input { display: flex; gap: 10px; }
        .chat-input input { flex: 1; }
        .status { padding: 10px; border-radius: 5px; margin-bottom: 15px; text-align: center; font-weight: bold; }
        .status.night { background: rgba(44,62,80,0.8); }
        .status.day { background: rgba(241,196,15,0.3); color: #f1c40f; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; justify-content: center; align-items: center; }
        .modal-content { background: #2c3e50; padding: 30px; border-radius: 10px; max-width: 500px; width: 90%; text-align: center; }
        .modal h2 { margin-bottom: 20px; color: #f1c40f; }
        .modal button { margin-top: 20px; }
        .player-cards { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px; }
        .player-card { background: rgba(255,255,255,0.1); border-radius: 8px; padding: 15px; width: calc(25% - 10px); text-align: center; cursor: pointer; transition: all 0.3s; }
        .player-card:hover { background: rgba(255,255,255,0.2); }
        .player-card.selected { background: rgba(231,76,60,0.3); border: 2px solid #e74c3c; }
        .connection-status { position: fixed; top: 10px; right: 10px; padding: 5px 10px; border-radius: 15px; font-size: 12px; z-index: 1000; }
        .connected { background: #2ecc71; color: white; }
        .disconnected { background: #e74c3c; color: white; }
        .connecting { background: #f39c12; color: white; }
        .player-count { color: #f1c40f; font-weight: bold; }
        @media (max-width: 768px) { .game-container { flex-direction: column; } .role-card, .player-card { width: calc(50% - 10px); } }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>联机狼人杀 - 实时版</h1>
            <p class="subtitle">与朋友在线体验经典的狼人杀游戏 - 实时同步！</p>
            <div class="share-link" id="shareLink">
                游戏加载中...
            </div>
        </header>
        
        <!-- 连接状态指示器 -->
        <div class="connection-status connecting" id="connectionStatus">
            连接中...
        </div>
        
        <div class="game-container">
            <div class="panel room-panel">
                <h2 class="panel-title">房间管理 <span class="player-count">(1/8)</span></h2>
                
                <div class="input-group">
                    <label for="playerName">玩家名称</label>
                    <input type="text" id="playerName" placeholder="输入你的名字" value="玩家1">
                </div>
                
                <div class="input-group">
                    <label for="roomId">房间号（加入时填写）</label>
                    <input type="text" id="roomId" placeholder="输入房间号加入游戏">
                </div>
                
                <div class="input-group">
                    <label for="playerCount">玩家数量</label>
                    <select id="playerCount">
                        <option value="6">6人局</option>
                        <option value="8" selected>8人局</option>
                        <option value="10">10人局</option>
                        <option value="12">12人局</option>
                    </select>
                </div>
                
                <button id="createRoom">创建房间</button>
                <button id="joinRoom">加入房间</button>
                
                <h3>房间玩家</h3>
                <ul class="player-list" id="playerList">
                    <!-- 玩家列表将由JavaScript动态生成 -->
                </ul>
                
                <button id="readyBtn">准备游戏</button>
                <button id="startGame" disabled>开始游戏</button>
            </div>
            
            <div class="panel game-panel">
                <h2 class="panel-title">游戏区域</h2>
                
                <div class="game-area">
                    <div class="status" id="gameStatus">
                        等待游戏开始
                    </div>
                    
                    <div class="game-info" id="gameInfo">
                        <p>等待游戏开始...</p>
                        <p>游戏规则：狼人每晚可以杀死一名玩家，白天所有玩家讨论并投票处决一名嫌疑玩家。</p>
                    </div>
                    
                    <div class="game-controls">
                        <button id="nightAction" disabled>夜晚行动</button>
                        <button id="dayDiscuss" disabled>白天讨论</button>
                        <button id="vote" disabled>投票</button>
                    </div>
                    
                    <div class="player-cards" id="playerCards">
                        <!-- 玩家卡片将由JavaScript动态生成 -->
                    </div>
                    
                    <div class="role-cards">
                        <div class="role-card werewolf">
                            <h3>狼人</h3>
                            <p>每晚可以杀死一名玩家</p>
                        </div>
                        <div class="role-card seer">
                            <h3>预言家</h3>
                            <p>每晚可以查验一名玩家身份</p>
                        </div>
                        <div class="role-card witch">
                            <h3>女巫</h3>
                            <p>拥有一瓶解药和一瓶毒药</p>
                        </div>
                        <div class="role-card villager">
                            <h3>平民</h3>
                            <p>没有特殊技能，通过推理找出狼人</p>
                        </div>
                    </div>
                    
                    <div class="chat-area">
                        <h3>游戏聊天</h3>
                        <div class="chat-messages" id="chatMessages">
                            <div>系统: 欢迎来到狼人杀游戏！</div>
                        </div>
                        <div class="chat-input">
                            <input type="text" id="chatInput" placeholder="输入聊天内容...">
                            <button id="sendChat">发送</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 角色分配模态框 -->
    <div class="modal" id="roleModal">
        <div class="modal-content">
            <h2>你的角色</h2>
            <div id="assignedRole">等待分配角色...</div>
            <button id="confirmRole">确认</button>
        </div>
    </div>

    <!-- 行动模态框 -->
    <div class="modal" id="actionModal">
        <div class="modal-content">
            <h2 id="actionTitle">夜晚行动</h2>
            <div id="actionDescription">请选择你要行动的目标</div>
            <div class="player-cards" id="actionPlayerCards">
                <!-- 行动玩家卡片将由JavaScript动态生成 -->
            </div>
            <button id="confirmAction">确认选择</button>
            <button id="cancelAction">取消</button>
        </div>
    </div>

    <script>
// 游戏数据
const gameData = {
    players: [],
    gameState: "waiting",
    currentPlayer: null,
    playerRole: null,
    roomId: null,
    isHost: false,
    selectedPlayer: null,
    playerName: ''
};

// DOM元素
const playerList = document.getElementById('playerList');
const playerCards = document.getElementById('playerCards');
const gameStatus = document.getElementById('gameStatus');
const gameInfo = document.getElementById('gameInfo');
const chatMessages = document.getElementById('chatMessages');
const chatInput = document.getElementById('chatInput');
const roleModal = document.getElementById('roleModal');
const assignedRole = document.getElementById('assignedRole');
const actionModal = document.getElementById('actionModal');
const actionTitle = document.getElementById('actionTitle');
const actionDescription = document.getElementById('actionDescription');
const actionPlayerCards = document.getElementById('actionPlayerCards');
const shareLink = document.getElementById('shareLink');
const connectionStatus = document.getElementById('connectionStatus');

// 模拟实时游戏客户端
class SimulationGameClient {
    constructor() {
        this.updateConnectionStatus('connected');
        this.setupSimulation();
    }
    
    updateConnectionStatus(status) {
        connectionStatus.className = `connection-status ${status}`;
        switch(status) {
            case 'connected':
                connectionStatus.textContent = '已连接(模拟模式)';
                break;
            case 'disconnected':
                connectionStatus.textContent = '连接断开';
                break;
            case 'connecting':
                connectionStatus.textContent = '连接中...';
                break;
        }
    }
    
    setupSimulation() {
        // 模拟其他玩家定时加入
        this.simulationInterval = setInterval(() => {
            if (gameData.isHost && gameData.players.length < 6 && Math.random() > 0.7) {
                this.addSimulatedPlayer();
            }
        }, 5000);
    }
    
    addSimulatedPlayer() {
        const playerId = 'sim_' + Date.now();
        const playerName = '玩家' + (gameData.players.length + 1);
        const player = {
            id: playerId,
            name: playerName,
            ready: Math.random() > 0.5,
            isHost: false,
            role: null,
            alive: true
        };
        
        gameData.players.push(player);
        updatePlayerList();
        addChatMessage(`系统: ${playerName} 加入了房间`);
        
        // 如果模拟玩家准备，检查是否可以开始游戏
        if (player.ready) {
            this.checkGameStart();
        }
    }
    
    async sendEvent(eventType, data) {
        console.log('发送事件:', eventType, data);
        
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        
        switch(eventType) {
            case 'create-room':
                return this.handleCreateRoom(data);
            case 'join-room':
                return this.handleJoinRoom(data);
            case 'toggle-ready':
                return this.handleToggleReady(data);
            case 'start-game':
                return this.handleStartGame(data);
            case 'chat-message':
                return this.handleChatMessage(data);
            case 'night-action':
                return this.handleNightAction(data);
            case 'vote':
                return this.handleVote(data);
            default:
                return { success: false, error: '未知事件类型' };
        }
    }
    
    handleCreateRoom(data) {
        gameData.roomId = Math.floor(1000 + Math.random() * 9000);
        gameData.isHost = true;
        
        const player = {
            id: 'player_' + Date.now(),
            name: data.playerName,
            ready: true,
            isHost: true,
            role: null,
            alive: true
        };
        
        gameData.players = [player];
        gameData.currentPlayer = player.id;
        gameData.playerName = data.playerName;
        
        updatePlayerList();
        updateShareLink();
        addChatMessage(`系统: 房间创建成功，房间号: ${gameData.roomId}`);
        addChatMessage('系统: 模拟玩家将陆续加入...');
        
        // 立即添加一个模拟玩家
        setTimeout(() => this.addSimulatedPlayer(), 1000);
        
        return { success: true, roomId: gameData.roomId };
    }
    
    handleJoinRoom(data) {
        gameData.roomId = data.roomId;
        gameData.isHost = false;
        
        const player = {
            id: 'player_' + Date.now(),
            name: data.playerName,
            ready: false,
            isHost: false,
            role: null,
            alive: true
        };
        
        // 模拟已有玩家
        gameData.players = [
            { id: 'host_001', name: '房主玩家', ready: true, isHost: true, role: null, alive: true },
            player
        ];
        
        gameData.currentPlayer = player.id;
        gameData.playerName = data.playerName;
        
        updatePlayerList();
        updateShareLink();
        addChatMessage(`系统: 成功加入房间 ${data.roomId}`);
        addChatMessage('系统: 等待房主开始游戏...');
        
        return { success: true };
    }
    
    handleToggleReady(data) {
        const player = gameData.players.find(p => p.id === gameData.currentPlayer);
        if (player) {
            player.ready = !player.ready;
            updatePlayerList();
            addChatMessage(`系统: ${player.name} ${player.ready ? '已准备' : '取消准备'}`);
            this.checkGameStart();
        }
        return { success: true };
    }
    
    handleStartGame(data) {
        if (!gameData.isHost) {
            return { success: false, error: '只有房主可以开始游戏' };
        }
        
        // 分配角色
        const roles = this.assignRoles(gameData.players.length);
        gameData.players.forEach((player, index) => {
            player.role = roles[index];
        });
        
        gameData.gameState = "night";
        const currentPlayer = gameData.players.find(p => p.id === gameData.currentPlayer);
        gameData.playerRole = currentPlayer.role;
        
        updateGameState();
        updatePlayerCards();
        showRoleModal(gameData.playerRole);
        addChatMessage("系统: 游戏开始！现在是第一个夜晚。");
        
        return { success: true };
    }
    
    handleChatMessage(data) {
        addChatMessage(`${data.playerName}: ${data.message}`);
        return { success: true };
    }
    
    handleNightAction(data) {
        const targetPlayer = gameData.players.find(p => p.id === data.targetPlayerId);
        if (targetPlayer) {
            if (gameData.playerRole === 'werewolf') {
                addChatMessage(`系统: 狼人选择了杀害 ${targetPlayer.name}`);
            } else if (gameData.playerRole === 'seer') {
                addChatMessage(`系统: 预言家查验了 ${targetPlayer.name}，身份是 ${getRoleDisplayName(targetPlayer.role)}`);
            }
        }
        return { success: true };
    }
    
    handleVote(data) {
        const targetPlayer = gameData.players.find(p => p.id === data.targetPlayerId);
        if (targetPlayer) {
            addChatMessage(`系统: 玩家投票给了 ${targetPlayer.name}`);
            // 模拟投票结果
            setTimeout(() => {
                targetPlayer.alive = false;
                updatePlayerCards();
                addChatMessage(`系统: ${targetPlayer.name} 被投票出局！`);
                
                gameData.gameState = "night";
                updateGameState();
                addChatMessage("系统: 进入下一个夜晚。");
            }, 2000);
        }
        return { success: true };
    }
    
    checkGameStart() {
        const allReady = gameData.players.every(p => p.ready);
        const canStart = allReady && gameData.players.length >= 3;
        document.getElementById('startGame').disabled = !(canStart && gameData.isHost);
    }
    
    assignRoles(playerCount) {
        const roles = {
            3: ['werewolf', 'seer', 'villager'],
            4: ['werewolf', 'werewolf', 'seer', 'witch'],
            5: ['werewolf', 'werewolf', 'seer', 'witch', 'villager'],
            6: ['werewolf', 'werewolf', 'seer', 'witch', 'villager', 'villager'],
            8: ['werewolf', 'werewolf', 'seer', 'witch', 'villager', 'villager', 'villager', 'villager']
        };
        
        const roleSet = roles[playerCount] || roles[6];
        return this.shuffleArray([...roleSet]);
    }
    
    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }
}

// 初始化游戏客户端
const gameClient = new SimulationGameClient();

// 更新玩家列表
function updatePlayerList() {
    playerList.innerHTML = '';
    gameData.players.forEach(player => {
        const li = document.createElement('li');
        const status = player.ready ? '✅ 准备' : '❌ 未准备';
        const hostIndicator = player.isHost ? ' 👑' : '';
        const isCurrentPlayer = player.id === gameData.currentPlayer ? ' (你)' : '';
        
        li.innerHTML = `${player.name}${isCurrentPlayer}${hostIndicator} <span>${status}</span>`;
        
        if (player.id === gameData.currentPlayer) {
            li.style.background = 'rgba(52, 152, 219, 0.3)';
        }
        
        playerList.appendChild(li);
    });
    
    // 更新玩家数量显示
    const playerCount = gameData.players.length;
    const maxPlayers = document.getElementById('playerCount').value;
    document.querySelector('.panel-title').innerHTML = 
        `房间管理 <span class="player-count">(${playerCount}/${maxPlayers})</span>`;
}

// 更新玩家卡片
function updatePlayerCards() {
    playerCards.innerHTML = '';
    gameData.players.forEach(player => {
        const card = document.createElement('div');
        card.className = 'player-card';
        card.dataset.id = player.id;
        card.innerHTML = `
            <h3>${player.name}</h3>
            <p>${player.alive ? '存活' : '已出局'}</p>
            ${player.role && !player.alive ? `<p>身份: ${getRoleDisplayName(player.role)}</p>` : ''}
        `;
        
        if (!player.alive) {
            card.style.opacity = '0.5';
        }
        
        if (player.id === gameData.currentPlayer) {
            card.style.border = '2px solid #3498db';
        }
        
        playerCards.appendChild(card);
    });
}

// 更新游戏状态
function updateGameState() {
    if (gameData.gameState === "waiting") {
        gameStatus.textContent = "等待游戏开始";
        gameStatus.className = "status";
        gameInfo.innerHTML = "<p>等待游戏开始...</p><p>游戏规则：狼人每晚可以杀死一名玩家，白天所有玩家讨论并投票处决一名嫌疑玩家。</p>";
        
        document.getElementById('nightAction').disabled = true;
        document.getElementById('dayDiscuss').disabled = true;
        document.getElementById('vote').disabled = true;
    } else if (gameData.gameState === "night") {
        gameStatus.textContent = "夜晚 - 请行动";
        gameStatus.className = "status night";
        
        if (gameData.playerRole === 'werewolf') {
            gameInfo.innerHTML = "<p>狼人请选择要杀害的目标</p>";
            document.getElementById('nightAction').disabled = false;
        } else if (gameData.playerRole === 'seer') {
            gameInfo.innerHTML = "<p>预言家请选择要查验的玩家</p>";
            document.getElementById('nightAction').disabled = false;
        } else if (gameData.playerRole === 'witch') {
            gameInfo.innerHTML = "<p>女巫请选择是否使用解药/毒药</p>";
            document.getElementById('nightAction').disabled = false;
        } else {
            gameInfo.innerHTML = "<p>请等待其他玩家行动</p>";
            document.getElementById('nightAction').disabled = true;
        }
        
        document.getElementById('dayDiscuss').disabled = true;
        document.getElementById('vote').disabled = true;
    } else if (gameData.gameState === "day") {
        gameStatus.textContent = "白天 - 自由讨论";
        gameStatus.className = "status day";
        gameInfo.innerHTML = "<p>现在是白天讨论时间，请讨论昨晚的事件并找出狼人</p>";
        
        document.getElementById('nightAction').disabled = true;
        document.getElementById('dayDiscuss').disabled = false;
        document.getElementById('vote').disabled = true;
    } else if (gameData.gameState === "voting") {
        gameStatus.textContent = "投票阶段";
        gameStatus.className = "status";
        gameInfo.innerHTML = "<p>请投票选出你认为的狼人</p>";
        
        document.getElementById('nightAction').disabled = true;
        document.getElementById('dayDiscuss').disabled = true;
        document.getElementById('vote').disabled = false;
    }
}

// 添加聊天消息
function addChatMessage(message) {
    const div = document.createElement('div');
    div.textContent = message;
    chatMessages.appendChild(div);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 显示角色分配
function showRoleModal(role) {
    assignedRole.textContent = getRoleDisplayName(role);
    roleModal.style.display = 'flex';
}

// 获取角色显示名称
function getRoleDisplayName(role) {
    const roleNames = {
        'werewolf': '🐺 狼人',
        'seer': '🔮 预言家', 
        'witch': '🧪 女巫',
        'villager': '👨‍🌾 平民',
        'hunter': '🏹 猎人'
    };
    return roleNames[role] || role;
}

// 显示行动模态框
function showActionModal(title, description) {
    actionTitle.textContent = title;
    actionDescription.textContent = description;
    
    actionPlayerCards.innerHTML = '';
    
    gameData.players.forEach(player => {
        if (player.id !== gameData.currentPlayer && player.alive) {
            const card = document.createElement('div');
            card.className = 'player-card';
            card.dataset.id = player.id;
            card.innerHTML = `<h3>${player.name}</h3>`;
            
            card.addEventListener('click', function() {
                const selected = actionPlayerCards.querySelector('.selected');
                if (selected) selected.classList.remove('selected');
                card.classList.add('selected');
                gameData.selectedPlayer = player.id;
            });
            
            actionPlayerCards.appendChild(card);
        }
    });
    
    actionModal.style.display = 'flex';
}

// 更新分享链接
function updateShareLink() {
    if (gameData.roomId) {
        const currentUrl = window.location.href.split('?')[0];
        shareLink.textContent = `${currentUrl}?room=${gameData.roomId}`;
    } else {
        shareLink.textContent = '创建房间后生成分享链接';
    }
}

// 事件监听
document.getElementById('createRoom').addEventListener('click', async function() {
    const playerName = document.getElementById('playerName').value;
    if (!playerName) {
        alert('请输入玩家名称');
        return;
    }
    
    await gameClient.sendEvent('create-room', {
        playerName: playerName,
        playerCount: document.getElementById('playerCount').value
    });
});

document.getElementById('joinRoom').addEventListener('click', async function() {
    const playerName = document.getElementById('playerName').value;
    const roomId = document.getElementById('roomId').value;
    if (!playerName) {
        alert('请输入玩家名称');
        return;
    }
    if (!roomId) {
        alert('请输入房间号');
        return;
    }
    
    await gameClient.sendEvent('join-room', {
        playerName: playerName,
        roomId: roomId
    });
});

document.getElementById('readyBtn').addEventListener('click', async function() {
    await gameClient.sendEvent('toggle-ready', {
        roomId: gameData.roomId
    });
});

document.getElementById('startGame').addEventListener('click', async function() {
    await gameClient.sendEvent('start-game', {
        roomId: gameData.roomId
    });
});

document.getElementById('sendChat').addEventListener('click', async function() {
    const message = chatInput.value;
    if (message.trim()) {
        await gameClient.sendEvent('chat-message', {
            roomId: gameData.roomId,
            message: message,
            playerName: gameData.playerName
        });
        chatInput.value = '';
    }
});

document.getElementById('nightAction').addEventListener('click', function() {
    if (gameData.gameState === "night") {
        if (gameData.playerRole === 'werewolf') {
            showActionModal('狼人行动', '请选择要杀害的玩家');
        } else if (gameData.playerRole === 'seer') {
            showActionModal('预言家行动', '请选择要查验的玩家');
        } else if (gameData.playerRole === 'witch') {
            showActionModal('女巫行动', '请选择要使用解药/毒药的玩家');
        }
    }
});

document.getElementById('dayDiscuss').addEventListener('click', function() {
    if (gameData.gameState === "day") {
        gameData.gameState = "voting";
        updateGameState();
        addChatMessage("系统: 讨论结束，开始投票！");
    }
});

document.getElementById('vote').addEventListener('click', function() {
    if (gameData.gameState === "voting") {
        showActionModal('投票', '请投票选出你认为的狼人');
    }
});

document.getElementById('confirmRole').addEventListener('click', function() {
    roleModal.style.display = 'none';
});

document.getElementById('confirmAction').addEventListener('click', async function() {
    if (gameData.selectedPlayer) {
        actionModal.style.display = 'none';
        
        if (gameData.gameState === "night") {
            await gameClient.sendEvent('night-action', {
                targetPlayerId: gameData.selectedPlayer
            });
            
            // 自动进入白天
            setTimeout(() => {
                gameData.gameState = "day";
                updateGameState();
                addChatMessage("系统: 天亮了！请大家讨论昨晚的事件。");
            }, 2000);
        } else if (gameData.gameState === "voting") {
            await gameClient.sendEvent('vote', {
                targetPlayerId: gameData.selectedPlayer
            });
        }
        
        gameData.selectedPlayer = null;
    } else {
        alert('请选择一个玩家');
    }
});

document.getElementById('cancelAction').addEventListener('click', function() {
    actionModal.style.display = 'none';
    gameData.selectedPlayer = null;
});

chatInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('sendChat').click();
    }
});

// 初始化
updatePlayerList();
updateGameState();
updateShareLink();
    </script>
</body>
</html>